import typing as t

from scapy.layers.http import *
from scapy.layers.inet import *

from .packet import PacketRecord


class HTTPPacketRecord(PacketRecord):
    def __init__(self, packet: Packet, mode: str = "b", packet_type="scapy"):
        super().__init__(packet, mode, packet_type)

        http_request = packet[HTTP]
        
        if isinstance(http_request.payload, HTTPRequest):
            host = http_request.getfieldval("Host").decode().strip()
            method = http_request.getfieldval("Method").decode().strip()
            path = http_request.getfieldval("Path").decode().strip()

            self.host = host
            self.url = f"{method} http://{host}{path}"
            self.type = "HTTPRequest"
        else:
            self.host = ""
            self.url = ""
            self.type = "HTTPResponse"

    def todict(self):
        d = super().todict()
        d.update({
            "Host": self.host,
            "Url": self.url,
            "Type": self.type
        })
        return d
